package cn.lcj.org.service.impl;


import cn.lcj.basic.service.impl.BaseServiceImpl;
import cn.lcj.org.domain.Department;
import cn.lcj.org.mapper.DepartmentMapper;
import cn.lcj.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * $
 *
 * @return $
 * @date $ $
 * @description $
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> departmentTree() {
        //查询全部将department对象放进一个数组里面
        List<Department> departments = departmentMapper.loadAll();
        //1.将所有部门信息保存在map中，方便根据id去获取部门信息，就不用查数据库了
        Map<Long, Department> map = new HashMap<>();
        for (Department department : departments) {
            //将数据放入map内存里面
            map.put(department.getId(), department);
        }
        //2.遍历所有的部门，如果是顶级部门[parent_id==null],加到部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if (department.getParent_id() == null) {
                deptTree.add(department);
                //3.如果不是顶级部门[parent_id!=null],找到自己的父部门，将自己加到父部门的children
            } else {
                //获取父部门的id - 获取父部门对象 - 获取父部门的children集合
                Long parentId = department.getParent_id();
                //根据id获取父部门
                Department parentDept = map.get(parentId);
                //防止数据表代码不对应空指针异常
                if (parentDept != null) {
                    parentDept.getChildren().add(department);
                }

            }
        }
        return deptTree;
    }
}
